import request, { getAjax, postAjax, putAjax, deleteAjax } from '@/utils/request'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Mutation, Action } from 'vuex'
import { Role } from './role'

export interface User {
  userId: number | null;
  username: string;
  nickName: string;
  userType: string;
  email: string;
  phoneNumber: string;
  sex: string;
  avatar: string;
  enable: boolean;
  roleIds?: Array<string>;
}

export interface LoginUser {
  token: string;
  loginTime: number;
  expireTime: number;
  ipaddr: string;
  loginLocation: string;
  browser: string;
  os: string;
  user: User;
}

export interface StateType {
  data: User;
  token: any;
  name: string;
  avatar: string;
  introduction: string;
  roles: Array<string>;
  permissions: Array<string>;
  roleOptions: Array<Role>;
}

export interface ModuleType {
  namespaced: boolean;
  state: StateType;
  mutations: {
    SET_ROLE_OPTIONS: Mutation<StateType>;
    SET_DATA: Mutation<StateType>;
    SET_TOKEN: Mutation<StateType>;
    SET_INTRODUCTION: Mutation<StateType>;
    SET_NAME: Mutation<StateType>;
    SET_AVATAR: Mutation<StateType>;
    SET_ROLES: Mutation<StateType>;
    SET_PERMISSIONS: Mutation<StateType>;
  };
  actions: {
    login: Action<StateType, StateType>;
    getInfo: Action<StateType, StateType>;
    logout: Action<StateType, StateType>;
    resetToken: Action<StateType, StateType>;
    getUserList: Action<StateType, StateType>;
    getUser: Action<StateType, StateType>;
    insertUser: Action<StateType, StateType>;
    updateUser: Action<StateType, StateType>;
    resetPwd: Action<StateType, StateType>;
    deleteUser: Action<StateType, StateType>;
    changeStatus: Action<StateType, StateType>;
  };
}

const storeModel: ModuleType = {
  namespaced: true,
  state: {
    data: {
      userId: null,
      username: '',
      nickName: '',
      userType: '',
      email: '',
      phoneNumber: '',
      sex: '',
      avatar: '',
      enable: true
    },
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    permissions: [],
    roleOptions: []
  },
  mutations: {
    SET_ROLE_OPTIONS: (state, data) => {
      state.roleOptions = data
    },
    SET_DATA: (state, data) => {
      state.data = data
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
  // user login
    login({ commit }, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        request({
          url: '/login',
          method: 'post',
          data: { username: username.trim(), password: password }
        }).then((res: any) => {
          commit('SET_TOKEN', res.token)
          setToken(res.token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // get user info
    getInfo({ commit }) {
      commit('SET_AVATAR', 'avatar')
      commit('SET_INTRODUCTION', 'introduction')
      return new Promise((resolve, reject) => {
        request({
          url: '/getInfo',
          method: 'get'
        }).then((res: any) => {
          commit('SET_NAME', res.user.nickName)
          if (res.roles && res.roles.length) {
            commit('SET_PERMISSIONS', res.permissions)
            commit('SET_ROLES', res.roles)
          } else {
            commit('SET_ROLES', ['edit'])
          }
          resolve(res.permissions)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // user logout
    logout({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        request({
          url: '/logout',
          method: 'post'
        }).then((res: any) => {
          commit('SET_TOKEN', res.token)
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          dispatch('tagsView/delAllViews', null, { root: true })
          // resetRouter()
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // remove token
    resetToken({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve(null)
      })
    },
    /**
     * 获取用户列表
     * @param {*} params
     */
    getUserList(_, params) {
      return getAjax('/system/user/list', params)
    },
    /**
     * 获取用户
     * @param {*} _
     * @param {*} userId
     */
    getUser({ commit }, userId) {
      let url = '/system/user/'
      if (userId) {
        url += `${userId}`
      }
      return new Promise((resolve, reject) => {
        getAjax(url, null).then((res: any) => {
          if (res && res.roles) {
            commit('SET_ROLE_OPTIONS', res.roles)
          }
          commit('SET_DATA', res.data)
          resolve(res)
        }).catch(err => { reject(err) })
      })
    },
    /**
     * 新增用户
     * @param {*} _
     * @param {*} data
     */
    insertUser(_, data) {
      return postAjax('/system/user', data)
    },
    /**
     * 更新用户
     * @param {*} _
     * @param {*} dat
     */
    updateUser(_, data) {
      return putAjax('/system/user', data)
    },
    resetPwd(_, data) {
      return putAjax('/system/user/resetPwd', data)
    },
    deleteUser(_, userId) {
      return deleteAjax(`/system/user/${userId}`, null)
    },
    changeStatus(_, data) {
      return putAjax('/system/user/changeStatus', data)
    }
  }
}
export default storeModel
